package io.framework.modules.soil.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.framework.common.annotation.LogOperation;
import io.framework.common.exception.ErrorCode;
import io.framework.common.utils.ConvertUtils;
import io.framework.common.utils.Result;
import io.framework.common.validator.AssertUtils;
import io.framework.modules.air.controller.UploadAirDataController;
import io.framework.modules.soil.dto.SoilDTO;
import io.framework.modules.soil.entity.SoilEntity;
import io.framework.modules.soil.service.SoilService;
import io.framework.modules.soil.utils.SoilFileCommonUtil;
import io.framework.modules.station.dto.StationDTO;
import io.framework.modules.station.service.StationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈土壤数据上传〉
 *
 * @Author GJQ
 * @Create 2020/5/20
 * @Since 1.0.0
 */
@RestController
@Api(tags = "土壤监测数据上传")
public class UploadSoilDataController {

    private Logger logger = LoggerFactory.getLogger(UploadAirDataController.class);

    @Value("${file.upload.path}")
    private String FILE_UPLOAD_PATH;

    @Autowired
    private SoilService soilService;

    @Autowired
    private StationService stationService;

    @GetMapping("soil/upload/checkData")
    @ApiOperation("验证土壤数据上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "时间年份 例：2020", paramType = "query", dataType = "Integer", required = true),
    })
    public Result checkData(@RequestParam Map<String, Object> params) {

        logger.info("=======================验证土壤数据上传=======================");

        String year = params.get("year").toString();
        Boolean flag = soilService.checkData(year);
        if(flag){
            return new Result().error(ErrorCode.UPLOAD_FILE_CHECK);
        }
        return new Result();
    }

    @PostMapping("soil/upload/datas/uploadFile")
    @ApiOperation("土壤数据上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "时间月份 例：2020-03", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "multipartFile", value = "文件", paramType = "query", dataType = "Integer", required = true),
    })
    @LogOperation("上传土壤站点监测数据")
    @RequiresPermissions("soil:info:upload")
    public Result readSoil(String year, MultipartFile multipartFile) {

        logger.info("=======================上传土壤站点监测数据=======================");

        AssertUtils.isBlank("year",ErrorCode.NOT_NULL);
        String filename = multipartFile.getOriginalFilename();
        if(StringUtils.isEmpty(filename)){
            return new Result().error(ErrorCode.UPLOAD_FILE_EMPTY);
        }
        File file = new File(FILE_UPLOAD_PATH + DateUtil.format(new Date(), "yyyy-MM-dd"));
        if (!file.exists()) {
            file.mkdirs();
        }
        File excelFile = new File(file, File.separator + DateUtil.format(new Date(), "HHmmss") + filename.substring(filename.indexOf(".")));
        try {
            multipartFile.transferTo(excelFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filePath =excelFile.getPath() ;
        List<SoilDTO> list = SoilFileCommonUtil.getSoilDTOInfo(filePath,year);
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(v -> {
                Map<String, Object> map = new HashMap<>(2);
                map.put("name", v.getVillageName());
                map.put("type", 3);
                List<StationDTO> stationDTOS = stationService.getStationInfoByParams(map);
                if (CollectionUtils.isNotEmpty(stationDTOS)) {
                    v.setStationId(stationDTOS.get(0).getId());
                }
            });
            logger.info("=======================清理历史数据=======================");
            soilService.deleteInfoByDate(year);
            soilService.insertBatch(ConvertUtils.sourceToTarget(list,SoilEntity.class));
        }
        return new Result().ok("上传成功");
    }
}
